#include "ota_runner.h"
#include "ota_http.h"
#include "log/log.h"
#include <unistd.h>
#include <sys/reboot.h>
#include <stdlib.h>
#include <signal.h>

/**
 * @brief 检查需不需要升级
 *
 * @param fileinfo
 * @return int 0需要，-1不需要
 */
static int ota_runner_checkUpdate(Fileinfo *fileinfo)
{
    if (fileinfo->major > MAJOR)
    {
        return 0;
    }
    else if (fileinfo->major == MAJOR && fileinfo->minor > MINOR)
    {
        return 0;
    }
    else if (fileinfo->major == MAJOR && fileinfo->minor == MINOR && fileinfo->patch > PATCH)
    {
        return 0;
    }

    return -1;
}

void ota_ruuner_signalHandler(int sig)
{
    log_info("Receive signal %d, exit", sig);
    exit(EXIT_SUCCESS);
}

void ota_runner_run()
{
    Fileinfo fileinfo;
    signal(SIGINT, ota_ruuner_signalHandler);
    signal(SIGTERM, ota_ruuner_signalHandler);

    while (1)
    {
        if (ota_http_getFileinfo(&fileinfo) < 0)
        {
            log_warn("Get fileinfo failed, retry after 10 minutes");
            sleep(600);
            continue;
        }
        if (ota_runner_checkUpdate(&fileinfo) < 0)
        {
            log_debug("No need to update, check again after 7 days");
            sleep(3600 * 24 * 7);
            continue;
        }
        if (ota_http_getFirmware(&fileinfo, TEMP_FILE) < 0)
        {
            log_warn("Get firmware failed, retry after 10 minutes");
            sleep(600);
            continue;
        }
        // 固件下载成功，之间诶重启
        log_info("Firmware download success, reboot in 5 seconds");
        sleep(5);
        reboot(RB_AUTOBOOT);
    }
}